<?php
/**
 * Created by PhpStorm.
 * User: Da Xiong
 * Date: 2019/2/28
 * Time: 14:14
 */

namespace App\HttpController\Wechat;


use App\HttpController\BaseController;
use App\Model\WechatsCustomModel;
use App\Utility\Cache;
use App\Utility\MiniProgram;

class IndexController extends BaseController
{

    public function index()
    {
        $request = $this->request();
        $params = $request->getRequestParam();
        $wechat = new MiniProgram($params['applet']);
        if($request->getMethod() == 'POST'){
            $body = $request->getBody();
            $bodyInfo = $wechat->getRaw($body);
            $custormModel = new WechatsCustomModel();
            $kefuMsg = $custormModel->where('applet',$params['applet'])->inRandomOrder()->first();
            if($kefuMsg) {
                $sendData = [
                    'type' => 'link',
                    'openid' => $bodyInfo['FromUserName'],//用户OPENID
                    'title' => $kefuMsg['title'],//消息标题
                    'description' => $kefuMsg['description'],//消息描述
                    'url' => $kefuMsg['url'],//链接地址
                    'thumb_url' => $kefuMsg['thumb_url'],//图片地址
                ];
                $wechat = new MiniProgram($params['applet']);
                return $wechat->sendCustomerMessage($sendData);
            }
//            $cache = new Cache();
//            $cache->onQueue('message-custorm');
//            return $cache->push(['openid'=>$bodyInfo['FromUserName'],'applet'=>$params['applet']]);
        }
        //验证token信息
        $echostr = $wechat->service($params);
        return $this->writeEcho($echostr);
    }
}
